﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interpreter.BuiltIns
{
	internal class OsFile  : Module
	{
		public override void Register(FunctionRegistry registry)
		{
			registry.Register(38, new OpenRead());
			registry.Register(39, new FileClose());
			registry.Register(40, new ReadAllText());
		}

		private class OpenRead : NativeFunction
		{
			public override Value Do(StackContext stackContext, Value[] args)
			{
				string path = stackContext.Args[0].Value0.ToString();
				// TODO: check path for existence
				// TODO: arg[1] should be the bool for text/binary

				string fullPath = System.IO.Path.Combine(stackContext.Metadata.ProgramRoot, path);

				return new Value(Value.TYPE_NATIVE_OBJECT, System.IO.File.OpenRead(fullPath));
			}
		}

		private class FileClose : NativeFunction
		{
			public override Value Do(StackContext stackContext, Value[] args)
			{
				System.IO.FileStream stream = (System.IO.FileStream)args[0].Value0;
				stream.Close();
				return Value.Null;
			}
		}

		private class ReadAllText : NativeFunction
		{
			public override Value Do(StackContext stackContext, Value[] args)
			{
				System.IO.FileStream stream = (System.IO.FileStream)args[0].Value0;

				int bytesRead = 1;
				int offset = 0;
				int i;
				byte[] buffer = new byte[256];
				StringBuilder output = new StringBuilder();
				while (bytesRead != 0)
				{
					bytesRead = stream.Read(buffer, offset, buffer.Length);
					for (i = 0; i < bytesRead; ++i)
					{
						output.Append((char)buffer[i]);
					}
				}
				return new Value(Value.TYPE_STRING, output.ToString());
			}
		}
	}
}
